<template>
  <div class="app-container">
    <el-tabs type="border-card">
      <!-- 仓库列表 -->
      <el-tab-pane label="仓库列表">
        <header class="app-header">
          <el-form inline label-width="140px">
            <el-form-item label="品牌：" prop="brand">
              <el-input
                v-model.trim="query.brand"
                clearable
                @clear="selected"
              />
            </el-form-item>
            <el-form-item label="名称：" prop="materialName">
              <el-input
                v-model.trim="query.materialName"
                clearable
                @clear="selected"
              />
            </el-form-item>
            <el-form-item label="规格：" prop="specifications">
              <el-input
                v-model.trim="query.specifications"
                clearable
                @clear="selected"
              />
            </el-form-item>
            <el-form-item label="图号：" prop="chartNo">
              <el-input
                v-model.trim="query.chartNo"
                clearable
                @clear="selected"
              />
            </el-form-item>
            <el-form-item label="物料类型：" prop="materialType">
              <el-select
                v-model="query.materialType"
                clearable
                @clear="selected"
              >
                <el-option
                  v-for="(label, key) in materialTypeMap"
                  :key="key"
                  :label="label"
                  :value="key"
                >{{ label }}</el-option
                >
              </el-select>
            </el-form-item>
            <el-form-item label="采购类型：" prop="purchaseType">
              <el-select
                v-model="query.purchaseType"
                clearable
                @clear="selected"
              >
                <el-option
                  v-for="(label, key) in purchaseTypeMap"
                  :key="key"
                  :label="label"
                  :value="key"
                >{{ label }}</el-option
                >
              </el-select>

              <el-button
                type="primary"
                size="small"
                @click="selected"
              >查询</el-button
              >
              <el-button plain size="small" @click="reset">重置</el-button>
            </el-form-item>
          </el-form>

          <div class="establish">
            <el-button
              type="primary"
              size="small"
              @click="storageOutAction"
            >出库</el-button
            >
            <el-button
              type="primary"
              size="small"
              @click="storageAddAction"
            >入库</el-button
            >
          </div>
        </header>

        <el-table
          :data="list"
          :header-row-style="{
            'background-color': '#E6E6E6',
            'font-weight': 'bold',
            color: '#333'
          }"
          :tree-props="{
            children: 'children',
            hasChildren: 'hasChildren'
          }"
          border
          height="650"
          style="width: 100%; margin-bottom: 20px"
          row-key="id"
        >
          <!-- @selection-change="handleSelectionChange" -->
          <!-- <el-table-column type="selection" width="55" /> -->
          <el-table-column
            show-overflow-tooltip
            align="center"
            prop="innerCode"
            label="内部订单编号"
            width="160px"
          />
          <el-table-column
            show-overflow-tooltip
            align="center"
            prop="chartNo"
            label="图号"
            width="180px"
          />
          <el-table-column
            show-overflow-tooltip
            align="center"
            prop="materialName"
            label="物料名称"
          />
          <el-table-column
            show-overflow-tooltip
            align="center"
            prop="amount"
            label="数量"
          />
          <el-table-column
            show-overflow-tooltip
            align="center"
            prop="materialType"
            label="物料类型"
          >
            <template slot-scope="scope">
              {{ materialTypeMap[scope.row.materialType] || "--" }}
            </template>
          </el-table-column>

          <el-table-column
            show-overflow-tooltip
            align="center"
            prop="materialType"
            label="采购类型"
          >
            <template slot-scope="scope">
              {{
                scope.row.materialType == 2
                  ? purchaseTypeMap[scope.row.purchaseType]
                  : "--"
              }}
            </template>
          </el-table-column>

          <el-table-column
            show-overflow-tooltip
            align="center"
            prop="brand"
            label="品牌"
          />
          <el-table-column
            show-overflow-tooltip
            align="center"
            prop="specifications"
            label="规格"
          />

          <el-table-column
            show-overflow-tooltip
            align="center"
            prop="unit"
            label="单位"
          />
          <el-table-column
            v-if="hasSeePriceRole"
            show-overflow-tooltip
            align="center"
            prop="price"
            label="价格"
          />
          <el-table-column
            v-if="hasSeePriceRole"
            show-overflow-tooltip
            align="center"
            prop="totalPrice"
            label="总价"
          />
          <el-table-column
            show-overflow-tooltip
            align="center"
            prop="comment"
            label="备注"
          />
        </el-table>

        <el-pagination
          :current-page="query.page"
          :total="total"
          :page-size="query.limit"
          style="padding: 30px 0; text-align: end"
          layout="total, prev, pager, next,jumper"
          @current-change="fetchData"
        />
      </el-tab-pane>

      <!-- 采购列表 -->
      <el-tab-pane label="采购列表">
        <purcharse-list type="platestorage" />
      </el-tab-pane>
    </el-tabs>

    <el-dialog :visible.sync="storageAdd.dialogshow" title="普通入库" destroy-on-close @close="closeDialog">
      <el-form
        v-if="storageAdd.dialogshow"
        ref="form"
        :model="storageAdd.form"
        :rules="storageAdd.rules"
        label-width="110px"
        inline
      >
        <el-form-item label="批次号" prop="recordCode">
          <el-input
            v-model.trim="storageAdd.form.recordCode"
            placeholder="请输入批次号"
          />
        </el-form-item>

        <el-form-item label="内部单号" prop="innerCode">
          <!--          <el-input-->
          <!--            v-model.trim="storageAdd.form.innerCode"-->
          <!--            placeholder="请输入内部单号"-->
          <!--          />-->
          <el-select
            v-model="storageAdd.form.innerCode"
            :remote-method="remoteInnerCode"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词">
            <el-option
              v-for="item in innerCodeOptions"
              :key="item.id"
              :label="item.insideCode"
              :value="item.insideCode"/>
          </el-select>
        </el-form-item>

        <el-form-item label="主管人员名称" prop="manager">
          <select-user :name-val="storageAdd.form.manager" @valChange="valChangeManager" />
          <!-- <select-user v-model="storageAdd.form.manager" /> -->
        </el-form-item>

        <el-form-item label="记账人员名称" prop="tallyer">
          <select-user :name-val="storageAdd.form.tallyer" @valChange="valChangeTallyer"/>
          <!-- <select-user v-model="storageAdd.form.tallyer" /> -->
        </el-form-item>

        <el-form-item label="经手人名称" prop="handlers">
          <select-user :name-val="storageAdd.form.handlers" @valChange="valChangeHandlers"/>
          <!-- <select-user v-model="storageAdd.form.handlers" /> -->
        </el-form-item>

        <el-form-item label="仓库人员名称" prop="storager">
          <el-input
            v-model.trim="storageAdd.form.storager"
            disabled
            placeholder="请输入仓库人员名称"
          />
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item label="物料类型" prop="materialType">
              <el-radio-group v-model="storageAdd.form.materialType">
                <el-radio :label="1">产品</el-radio>
                <el-radio :label="2">材料</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              v-if="storageAdd.form.materialType == 2"
              label="采购类型"
              prop="purchaseType"
            >
              <el-radio-group v-model="storageAdd.form.purchaseType">
                <el-radio :label="1">刀具</el-radio>
                <el-radio :label="2">物料</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="物料名称" prop="materialName">
          <!--          <el-input-->
          <!--            v-model.trim="storageAdd.form.materialName"-->
          <!--            placeholder="请输入物料名称"-->
          <!--          />-->
          <el-select
            v-model="storageAdd.form.materialName"
            :remote-method="remoteMaterialName"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词">
            <el-option
              v-for="item in materialNameOptions"
              :key="item.id"
              :label="item.picName"
              :value="item.picName"/>
          </el-select>
        </el-form-item>

        <el-form-item label="图号" prop="chartNo">
          <!--          <el-input-->
          <!--            v-model.trim="storageAdd.form.chartNo"-->
          <!--            placeholder="请输入图号"-->
          <!--          />-->
          <el-select
            v-model="storageAdd.form.chartNo"
            :remote-method="remoteMaterialName"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词">
            <el-option
              v-for="item in materialNameOptions"
              :key="item.id"
              :label="item.picCode"
              :value="item.picCode"/>
          </el-select>
        </el-form-item>

        <el-form-item label="品牌" prop="brand">
          <el-input
            v-model.trim="storageAdd.form.brand"
            placeholder="请输入品牌"
          />
        </el-form-item>

        <el-form-item label="规格型号" prop="specifications">
          <el-input
            v-model.trim="storageAdd.form.specifications"
            placeholder="请输入规格型号"
          />
        </el-form-item>

        <el-form-item label="数量" prop="amount">
          <el-input-number
            v-model="storageAdd.form.amount"
            :min="1"
            placeholder="请输入入库数量"
          />
        </el-form-item>

        <el-form-item label="单位" prop="unit">
          <el-input
            v-model.trim="storageAdd.form.unit"
            :maxlength="5"
            placeholder="请输入单位"
          />
        </el-form-item>

        <el-form-item v-show="hasSeePriceRole" label="价格" prop="price">
          <el-input-number
            v-model="storageAdd.form.price"
            :min="1"
            placeholder="请输入价格"
          />
        </el-form-item>

        <el-form-item label="备注" prop="comment">
          <el-input
            v-model.trim="storageAdd.form.comment"
            :row="2"
            type="textarea"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button
          :loading="storageAdd.loading"
          type="primary"
          @click="confirmStorageAdd"
        >确 定</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="storageOut.dialogshow"
      title="出库操作"
      width="1000px"
      @close="closeStorageOut"
    >
      <el-form
        ref="outform"
        :model="storageOut.form"
        :rules="storageOut.rules"
        inline
        label-width="140px"
      >
        <div
          v-for="(item, index) in storageOut.form.outBoundItems"
          :key="item.rid"
        >
          <el-form
            :ref="'outAddform' + item.rid"
            :model="storageOut.form"
            inline
          >
            <el-form-item
              :prop="'outBoundItems.' + index + '.materialName'"
              :rules="storageOut.rules.materialName"
              label="物料或产品"
              label-width="100px"
            >
              <el-select
                v-model="item.materialName"
                :remote-method="remoteMethod"
                :loading="storageOut.query.loading"
                filterable
                remote
                reserve-keyword
                placeholder="请输入物料或产品的关键字"
                @change="changeQueryItem"
              >
                <!--                :disabled="citem.disabled"-->
                <el-option
                  v-for="citem in remoteList"
                  :key="citem.key"
                  :label="citem.key"
                  :value="citem.picName"
                />
              </el-select>
            </el-form-item>

            <el-form-item
              :prop="'outBoundItems.' + index + '.productPurchaseId'"
              :rules="storageOut.rules.productPurchaseId"
              label="请购单号"
              label-width="80px"
            >
              <el-input
                v-model.trim="item.productPurchaseId"
                placeholder="请输入请购单号"
              />
            </el-form-item>

            <!-- <el-form-item
              :prop="'outBoundItems.' + index + '.productPurchaseId'"
              :rules="storageOut.rules.productPurchaseId"
              label="请购单号"
              label-width="80px"
            >
              <el-input
                v-model.trim="item.productPurchaseId"
                placeholder="请输入请购单号"
              />
            </el-form-item> -->

            <el-form-item
              :prop="'outBoundItems.' + index + '.amount'"
              :rules="storageOut.rules.amount"
              label="数量"
              label-width="60px"
            >
              <el-input-number
                :min="1"
                :max="item.maxAmount"
                v-model="item.amount"
                placeholder="请输入数量"
              />
            </el-form-item>

            <el-form-item v-if="storageOut.form.outBoundItems.length > 1">
              <el-button
                type="primary"
                size="small"
                @click="deleteRow(item)"
              >删除</el-button
              >
            </el-form-item>
          </el-form>
        </div>

        <div
          class="dialog-form__add"
          style="text-align: center; padding: 30px 0 10px"
        >
          <el-button
            type="default"
            size="small"
            style="width: 200px"
            @click.stop="addStorageOutItem"
          ><i class="el-icon-plus" />新增</el-button
          >
        </div>

        <el-row>
          <el-col :span="8">
            <el-form-item
              label="是否生成pdf"
              prop="ifPdf"
              label-width="100px"
              style="width: 100%"
            >
              <el-radio-group
                v-model="storageOut.form.ifPdf"
                style="width: 200px"
              >
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item
              :rules="storageOut.rules.orderCode"
              label="订单编号"
              label-width="80px"
              prop="orderCode"
            >
              <!--              <el-input-->
              <!--                class="s-input"-->
              <!--                v-model.trim="storageOut.form.orderCode"-->
              <!--                placeholder="请输入订单编号"-->
              <!--              />-->
              <el-select
                v-model="storageOut.form.orderCode"
                :remote-method="remoteStorageOutInnerCode"
                filterable
                remote
                reserve-keyword
                placeholder="请输入关键词">
                <el-option
                  v-for="item in storageOutInnerCodeOptions"
                  :key="item.id"
                  :label="item.insideCode"
                  :value="item.insideCode"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <template v-if="storageOut.form.ifPdf">
          <el-form-item label="项目编号" prop="projectCode">
            <el-input
              v-model.trim="storageOut.form.projectCode"
              class="s-input"
              placeholder="请输入项目编号"
            />
          </el-form-item>

          <!-- <el-form-item label="订单编号" prop="orderCode">
            <el-input
              class="s-input"
              v-model.trim="storageOut.form.orderCode"
              placeholder="请输入订单编号"
            />
          </el-form-item> -->

          <el-form-item label="客户名称" prop="clientName">
            <el-input
              v-model.trim="storageOut.form.clientName"
              class="s-input"
              placeholder="请输入客户名称"
            />
          </el-form-item>

          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model.trim="storageOut.form.phone"
              class="s-input"
              placeholder="请输入手机号"
            />
          </el-form-item>

          <el-form-item label="传真" prop="fax">
            <el-input
              v-model.trim="storageOut.form.fax"
              class="s-input"
              placeholder="请输入传真"
            />
          </el-form-item>

          <el-form-item label="地址" prop="address">
            <el-input
              v-model.trim="storageOut.form.address"
              class="s-input"
              placeholder="请输入地址"
            />
          </el-form-item>

          <el-form-item label="送货日期" prop="deliveryDate">
            <el-date-picker
              v-model="storageOut.form.deliveryDate"
              :editable="false"
              :picker-options="pickerOptions"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
            />
          </el-form-item>

          <el-form-item label="送货单位" prop="deliveryUnit">
            <el-input
              v-model.trim="storageOut.form.deliveryUnit"
              class="s-input"
              placeholder="请输入送货单位"
            />
          </el-form-item>
        </template>

        <el-form-item prop="comments" label="备注" style="padding">
          <el-input
            v-model.trim="storageOut.form.comments"
            :row="5"
            class="s-input"
            type="textarea"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button
          :loading="storageOut.loading"
          type="primary"
          @click="confirmStorageOut"
        >确 定</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="storageOut.pdfDialogShow"
      title="pdf表单下载"
      @close="closePdfDialog"
    >
      <div class="">
        <p>
          路径地址：<a :href="storageOut.pdfUrl" target="blank">{{
            storageOut.pdfUrl
          }}</a>
        </p>
        <el-button>
          <a :href="storageOut.pdfUrl" target="blank">下载</a>
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import user from '../../api/acl/user.js'
import { random } from '../../utils/index'
import { materialTypeMap, purchaseTypeMap } from '../../utils/const'
import PurcharseList from '../purchaseList/index.vue'
import SelectUser from './select-user.vue'

// 出库单项数据
const outBoundItem = () => ({
  rid: random(),
  productPurchaseId: '',
  storageId: '',
  materialName: '',
  specifications: '',
  amount: ''
})

export default {
  name: 'Purchaselist',

  components: {
    PurcharseList,
    SelectUser
  },

  data() {
    const validateAmount = (rule, val, callback) => {
      if (!val) {
        callback(new Error('请输入数量'))
      }

      callback()
    }

    const validatePhone = (rule, val, callback) => {
      if (!/^1[0-9]{10}$/.test(val)) {
        callback(new Error('输入的手机号格式不正确'))
      }

      callback()
    }

    const validateStorageId = (rule, val, callback) => {
      if (!/^[0-9][0-9]*$/.test(val)) {
        callback(new Error('输入的请购单号不是数字，或者格式错误'))
      }

      callback()
    }

    return {
      query: {
        brand: '',
        materialName: '',
        specifications: '',
        purchaseType: null,
        materialType: null,
        chartNo: '',
        page: 1,
        limit: 10
      },
      list: [],
      total: 1,
      storageAdd: {
        dialogshow: false,
        loading: false,
        rules: {
          recordCode: [
            {
              required: true,
              message: '请输入批次号',
              trigger: 'blur'
            }
          ],
          manager: [
            {
              required: true,
              message: '请输入主管人员名称',
              trigger: 'change'
            }
          ],
          // storager: [
          // 	{
          // 		required: true,
          // 		message: "请输入仓库人员名称",
          // 		trigger: "blur",
          // 	},
          // ],
          tallyer: [
            {
              required: true,
              message: '请输入记账人员名称',
              trigger: 'change'
            }
          ],
          handlers: [
            {
              required: true,
              message: '请输入经手人名称',
              trigger: 'change'
            }
          ],
          materialName: [
            {
              required: true,
              message: '请输入物料名称',
              trigger: 'blur'
            }
          ],
          chartNo: [
            {
              required: true,
              message: '请输入图号',
              trigger: 'blur'
            }
          ],
          //   brand: [
          //     {
          //       required: true,
          //       message: "请输入品牌",
          //       trigger: "blur"
          //     }
          //   ],
          //   specifications: [
          //     {
          //       required: true,
          //       message: "请输入规格型号",
          //       trigger: "blur"
          //     }
          //   ],
          //   unit: [
          //     {
          //       required: true,
          //       message: "请输入单位",
          //       trigger: "blur"
          //     }
          //   ],
          materialType: [
            {
              required: true,
              message: '请选择物料类型',
              trigger: 'change'
            }
          ],
          purchaseType: [
            {
              required: true,
              message: '请选择采购类型',
              trigger: 'change'
            }
          ]
        },
        form: {
          recordCode: '',
          manager: '',
          storager: sessionStorage.getItem('userName'),
          tallyer: '',
          handlers: '',
          innerCode: '',
          chartNo: '',
          brand: '',
          materialName: '',
          specifications: '',
          materialType: null,
          purchaseType: null,
          unit: '',
          price: 0,
          comment: '',
          amount: 1,
          operator: ''
        }
      },
      materialTypeMap,
      purchaseTypeMap,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 24 * 3600 * 1000
        }
      },
      storageOut: {
        dialogshow: false,
        loading: false,
        query: {
          options: [],
          value: '',
          loading: false
        },
        rules: {
          orderCode: [
            {
              required: true,
              message: '请输入订单编号',
              trigger: 'blur'
            }
          ],
          productPurchaseId: [
            {
              required: true,
              message: '请输入请购单号',
              trigger: 'blur'
            }
          ],
          materialName: [
            {
              required: true,
              message: '请选择产品或物料',
              trigger: 'change'
            }
          ],
          ifPdf: [
            {
              required: true,
              message: '请选择是否生成表单',
              trigger: 'change'
            }
          ],
          address: [
            {
              required: true,
              message: '请输入地址',
              trigger: 'blur'
            }
          ],
          phone: [
            {
              required: true,
              message: '请输入手机号',
              trigger: 'blur'
            },
            {
              validator: validatePhone,
              message: '手机号格式不正确',
              trigger: 'blur'
            }
          ],
          amount: [
            {
              validator: validateAmount,
              required: true,
              message: '请输入数量',
              trigger: 'blur'
            }
          ],
          projectCode: [
            {
              required: true,
              message: '请输入项目编号',
              trigger: 'blur'
            }
          ],
          clientName: [
            {
              required: true,
              message: '请输入客户名称',
              trigger: 'blur'
            }
          ],
          orderCode: [
            {
              required: true,
              message: '请输入订单编号',
              trigger: 'blur'
            }
          ],
          deliveryDate: [
            {
              required: true,
              message: '请输入送货日期',
              trigger: 'change'
            }
          ],
          deliveryUnit: [
            {
              required: true,
              message: '请输入送货单位',
              trigger: 'blur'
            }
          ]
        },
        form: {
          address: '', // 地址
          phone: '', // 手机
          fax: '',
          projectCode: '',
          clientName: '',
          orderCode: '',
          deliveryDate: '',
          comments: '',
          deliveryUnit: '', // 送货单位
          operator: '', // 操作者
          ifPdf: '',
          outBoundItems: [outBoundItem()]
        },
        pdfUrl: '',
        pdfDialogShow: false
      },
      searchManagerLoading: false,
      searchManagerList: [],
      searchHandlersLoading: false,
      searchHandlersList: [],
      searchTallyerLoading: false,
      searchTallyerList: [],
      innerCodeOptions: [],
      materialNameOptions: [],
      storageOutInnerCodeOptions: []
    }
  },

  computed: {
    outBoundItemsKeys() {
      return this.storageOut.form.outBoundItems.map(item => item.id)
    },
    remoteList() {
      return (
        this.storageOut.query.options.map(item => {
          // item.disabled =
          //   this.outBoundItemsKeys.some(kitem => kitem == item.id) ||
          //   item.amount == 0;
          item.key = item.picName + '(' + item.picCode + ')'
          return item
        }) || []
      )
    },
    // 是否是仓库人员
    isPlatestorage() {
      return window.sessionStorage.getItem('department') == 10
    },
    // 是否是管理员
    isAdmin() {
      return window.sessionStorage.getItem('department') == 1
    },
    // 是否是采购人员
    isPurchaser() {
      return window.sessionStorage.getItem('department') == 11
    },
    // 是否具有查看价格的权限
    hasSeePriceRole() {
      return this.isPlatestorage || this.isAdmin || this.isPurchase
    }
  },

  created() {
    this.getList()
  },

  methods: {
    valChangeHandlers(val) {
      console.log(val)
      this.storageAdd.form.handlers = val
    },
    valChangeTallyer(val) {
      console.log(val)
      this.storageAdd.form.tallyer = val
    },
    valChangeManager(val) {
      console.log(val)
      this.storageAdd.form.manager = val
    },
    // 搜索主管人员方法
    searchManager() {
      this.searchManagerLoading = true
      this.searchManagerLoading = false
      this.searchManagerList = []
    },
    // 搜索记账人员方法
    searchTallyer() {
      this.searchTallyerLoading = true
      this.searchTallyerLoading = false
      this.searchTallyerList = []
    },
    // 搜索经手人员方法
    searchHandlers() {
      this.searchHandlersLoading = true
      this.searchHandlersLoading = false
      this.searchHandlersList = []
    },
    closePdfDialog() {
      this.storageOut.pdfDialogShow = false
      this.storageOut.pdfUrl = ''
    },
    reset() {
      this.query = {
        brand: '',
        materialName: '',
        specifications: '',
        purchaseType: null,
        materialType: null,
        chartNo: '',
        page: 1,
        limit: 10
      }
      this.getList()
    },
    selected() {
      this.getList()
    },
    fetchData(val) {
      this.query.page = val
      this.getList()
    },
    getList() {
      user.listPlateStorage(this.query).then(response => {
        this.total = response.total
        this.list = response.list
      })
    },
    // 入库窗口显示
    storageAddAction(row) {
      this.storageAdd.form = {
        recordCode: '',
        manager: '',
        storager: sessionStorage.getItem('userName'),
        tallyer: '',
        handlers: '',
        innerCode: '',
        chartNo: '',
        brand: '',
        materialName: '',
        specifications: '',
        materialType: null,
        purchaseType: null,
        unit: '',
        price: 0,
        comment: '',
        amount: 1,
        operator: ''
      }
      this.storageAdd.dialogshow = true
    },
    closeDialog() {
      this.storageAdd.form = {
        recordCode: '',
        manager: '',
        storager: sessionStorage.getItem('userName'),
        tallyer: '',
        handlers: '',
        innerCode: '',
        chartNo: '',
        brand: '',
        materialName: '',
        specifications: '',
        materialType: null,
        purchaseType: null,
        unit: '',
        price: 0,
        comment: '',
        amount: 1,
        operator: ''
      }
      this.$refs.form.resetFields()
    },
    // 确定入库
    confirmStorageAdd() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const {
            storageAdd: { form }
          } = this
          form.operator = window.sessionStorage.getItem('userName')
          this.storageAdd.loading = true

          if (form.materialType == 1) delete form.purchaseType

          user
            .storageAdd(form)
            .then(res => {
              this.$message({
                message: '入库成功',
                type: 'success'
              })
              this.storageAdd.loading = false
              this.storageAdd.dialogshow = false
              this.$refs.form.resetFields()
              this.getList()
            })
            .catch(() => {
              this.storageAdd.loading = false
            })
        } else {
          return false
        }
      })
    },
    // 产品出库
    storageOutAction() {
      this.storageOut.dialogshow = true
    },
    // 删除一项出库物品
    deleteRow(rowItem) {
      this.storageOut.form.outBoundItems.forEach((item, index) => {
        if (item.rid == rowItem.rid) {
          this.storageOut.form.outBoundItems.splice(index, 1)
        }
      })
    },
    remoteStorageOutInnerCode(query) {
      if (query !== '') {
        user
          .getOrderCode(query)
          .then(response => {
            this.storageOutInnerCodeOptions = response
          })
      } else {
        this.storageOutInnerCodeOptions = []
      }
    },
    remoteMaterialName(query) {
      if (query !== '' && this.storageAdd.form.innerCode !== '') {
        user
          .getProductImportByOrder(query, this.storageAdd.form.innerCode)
          .then(response => {
            this.materialNameOptions = response
          })
      } else {
        this.materialNameOptions = []
      }
    },
    remoteInnerCode(query) {
      if (query !== '') {
        user
          .getOrderCode(query)
          .then(response => {
            this.innerCodeOptions = response
          })
      } else {
        this.innerCodeOptions = []
      }
    },
    // 远程搜索仓库信息
    remoteMethod(query) {
      // if (query !== "") {
      //   this.storageOut.query.loading = true;
      //
      //   user
      //     .listPlateStorage({
      //       page: 1,
      //       limit: 10000,
      //       materialName: query
      //     })
      //     .then(response => {
      //       this.storageOut.query.options = response.list || [];
      //       this.storageOut.query.loading = false;
      //     });
      // } else {
      //   this.options = [];
      // }
      if (query !== '' && this.storageOut.form.orderCode !== '') {
        this.storageOut.query.loading = true
        user
          .getProductImportByOrder(query, this.storageOut.form.orderCode)
          .then(response => {
            this.storageOut.query.options = response

            this.storageOut.query.loading = false
          })
      } else {
        this.remoteList = []
      }
    },
    // 验证出库弹框的所有项
    validateItems() {
      const cb = (_ref, resolve, reject) => {
        _ref.validate(valid => (valid ? resolve(true) : reject()))
      }
      const { outBoundItems } = this.storageOut.form

      return new Promise((resolve, reject) => {
        const result = []
        for (let i = 0, len = outBoundItems.length; i < len; i++) {
          const formRefs = this.$refs[`outAddform${outBoundItems[i].rid}`]

          if (Array.isArray(formRefs)) {
            formRefs[0].validate(valid => result.push(valid))
          } else {
            cb(formRefs, resolve, reject)
          }
        }

        result.every(item => item) ? resolve(true) : reject(false)
      })
    },
    // 验证表单的
    validateForm() {
      return new Promise((resolve, reject) => {
        this.$refs.outform.validate(valid => {
          valid ? resolve(true) : reject()
        })
      })
    },
    // 增加新的出库项目
    addStorageOutItem() {
      this.validateItems().then(() => {
        this.storageOut.form.outBoundItems.push(outBoundItem())
      })
    },
    // 选择项
    changeQueryItem(val) {
      const selectedOption = this.storageOut.query.options.find(
        item => item.id == val
      )
      selectedOption.maxAmount = selectedOption.amount

      this.storageOut.query.options.forEach(item => {
        item.disabled = this.outBoundItemsKeys.some(kitem => kitem == item.id)
      })

      this.storageOut.form.outBoundItems.forEach(item => {
        item.materialName = selectedOption.materialName
        item.specifications = selectedOption.specifications
      })
    },
    // 获取参数
    getOutParams() {
      const { form } = this.storageOut
      const data = {
        outBoundItems: form.outBoundItems.map(
          ({
            productPurchaseId,
            id,
            orderCode,
            materialName,
            specifications,
            amount
          }) => ({
            productPurchaseId: +productPurchaseId,
            orderCode: orderCode,
            storageId: id,
            materialName,
            specifications,
            amount
          })
        ),
        ifPdf: form.ifPdf,
        operator: window.sessionStorage.getItem('userName'),
        comments: form.comments,
        orderCode: form.orderCode
      }

      if (form.ifPdf) {
        Object.assign(data, {
          address: form.address, // 地址
          phone: form.phone, // 手机号
          fax: form.fax, // 传真
          projectCode: form.projectCode, // 项目编号
          clientName: form.clientName, // 客户名称
          orderCode: form.orderCode, // 订单编号
          deliveryDate: form.deliveryDate // 送货日期
        })
      }

      return data
    },
    resetStorageOut() {
      this.$refs.outform.resetFields()
      this.$set(this.storageOut.form, 'outBoundItems', [outBoundItem()])
    },
    closeStorageOut() {
      this.resetStorageOut()
    },
    // 确认出库
    async confirmStorageOut() {
      // Promise.all([this.validateItems(), this.validateForm()])
      try {
        const itemsValid = await this.validateItems()
        const formValid = await this.validateForm()

        if (itemsValid && formValid) {
          this.storageOut.loading = true
          const data = this.getOutParams()

          user
            .storageOutbound(data)
            .then(res => {
              this.storageOut.pdfUrl = res || ''
              this.storageOut.loading = false
              // if (data.ifPdf) {
              //   this.storageOut.pdfDialogShow = true;
              // }
              this.resetStorageOut()
              this.getList()
              this.storageOut.dialogshow = false
              this.$message({
                message: '出库成功',
                type: 'success'
              })
            })
            .catch(err => {
              this.storageOut.loading = false
            })
        }
      } catch (error) {
        console.log('error: ', error)
      }
    },
    // 勾选数据
    handleSelectionChange(rows) {
      this.storageOut.ids = rows.map(item => item.id)
    }
  }
}
</script>

<style>
.establish {
  text-align: right;
}

.s-input {
  min-width: 220px;
}
</style>
